package com.starmark.gateway.springcloud.provider.service.impl;

import com.alibaba.fastjson.JSON;
import com.starmark.gateway.springcloud.provider.dto.GatewayProjectDto;
import com.starmark.gateway.springcloud.provider.dto.ProjectSpecUrlDto;
import com.starmark.gateway.springcloud.provider.service.ICacheService;
import com.starmark.gateway.springcloud.provider.service.IProjectSpecUrlService;
import com.starmark.gateway.springcloud.provider.service.IRouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 工程特殊URL服务
 *
 * @author starmark
 * @since 2020/10/8 000813:09
 **/
@Service
public class ProjectSpecUrlServiceImpl implements IProjectSpecUrlService {

    private final static String PROJECT_SPEC_URL_REDIS_KEY = "starmark:gateway:project:specurl:";
    @Autowired
    private ICacheService cacheService;

    @Autowired
    private IRouteService routeService;


    @Override
    public List<ProjectSpecUrlDto> findSpecUrlListByProjectId(String projectId) {
        Map<Object, Object> specUrlMap = cacheService.getMapByKey(PROJECT_SPEC_URL_REDIS_KEY + projectId);
        if (specUrlMap == null || specUrlMap.isEmpty()) {
            return Collections.emptyList();
        }
        return specUrlMap.values().stream().map(specUrlDto ->
                JSON.parseObject(Objects.requireNonNull(JSON.parse(specUrlDto.toString())).toString(), ProjectSpecUrlDto.class)).filter(specUrlDto -> specUrlDto.getStatus() == 1).collect(Collectors.toList());

    }

    @Override
    public List<ProjectSpecUrlDto> findSpecUrlListByProjectCode(String projectCode) {
        GatewayProjectDto gatewayProjectDto = routeService.getGatewayProject(projectCode);
        Assert.notNull(gatewayProjectDto, "工程不存在:" + projectCode);
        return this.findSpecUrlListByProjectId(gatewayProjectDto.getId());
    }
}
